<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\MemberMiniapp;
use app\common\model\MemberMiniappAudit;
use app\common\model\MemberMiniappOrder;
use app\common\model\MemberMiniappTemplate;
use app\manage\model\admin\MiniappModule;
use app\manage\model\Member;
use app\Request;
use buwang\base\MemberBaseController;
use buwang\facade\WechatProgram;
use buwang\service\MiniappService;
use buwang\traits\CrudControllerTrait;
use filter\Inspect;
use think\facade\View;
use app\common\model\Plugin;
use app\common\model\MemberPluginOrder;
use app\common\model\MiniappTerm;

class Miniapp extends MemberBaseController
{
    use CrudControllerTrait;

    protected $model = null;//模型实例

    protected function initialize()
    {
        parent::initialize();
        $this->model = new \app\common\model\Miniapp();
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->layout && $this->app->view->engine()->layout($this->layout);

        $count = $this->model->where(['status' => 1])
            ->where("(is_diy = 0 OR (is_diy = 1 AND diy_member_ids LIKE '%,{$this->uid},%'))")
            ->count();
        //已购买的应用列表
        $miniapp_id = MemberMiniapp::where("member_id", $this->uid)->column('miniapp_id', 'miniapp_id');

        $list = $this->model->where(['status' => 1])
            ->where("(is_diy = 0 OR (is_diy = 1 AND diy_member_ids LIKE '%,{$this->uid},%'))")
            ->order('id asc')->select()->toArray();
        foreach ($list as &$item) {
            $item['buy'] = false;
            if (isset($miniapp_id[$item['id']])) $item['buy'] = true;
            $price = [];
            $miniappModules = MiniappModule::where('miniapp_id', $item['id'])->select()->toArray();

            foreach ($miniappModules as &$miniappModule) {
                $price = array_merge($price, array_column($miniappModule['price_list'], 'price'));
            }
            //获取功能套餐组的套餐价格
            $item['min_price'] = sprintf('%.2f', min($price ?: [0]));
            $item['max_price'] = sprintf('%.2f', max($price ?: [0]));
            //处理租户应用logo
            if (!strstr($item['logo_image'], 'http')) {
                $item['logo_image'] = bw_config('web_config.web_url') . '/' . $item['logo_image'];
            }
        }

        $data = [
            'default_miniapp_dir' => $this->user->default_miniapp_dir??'',
            'total' => $count,
            'list' => $list,
        ];
        if ($this->request->isPost()) {
            return $this->success('success', $data);
        }
        View::assign(compact('list'));
        return view();
    }

    /**
     * 应用详情页
     * @param int $id
     * @return \think\Response|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail($id = 0)
    {
        $this->layout && $this->app->view->engine()->layout($this->layout);
        $detail = $this->model->where(['id' => $id, 'status' => 1])->find();
        if (!$detail) return $this->error_jump('应用不存在');
        //富文本转移
        $detail['content'] = urldecode(urldecode(html_entity_decode($detail['content'])));
        //应用基础功能
        $baseModule = MiniappModule::where(['miniapp_id' => $id, 'type' => 1])->find();
        if (!$baseModule) return $this->error_jump('应用有误,无基础功能');
        if (!$baseModule['price_list']) return $this->error_jump('该应用功能不完整,请联系客服在总后台设置购买套餐');
        //TODO：查询最近购买的基础功能
        $miniappOrder = MemberMiniappOrder::where(['member_id' => $this->uid, 'miniapp_id' => $id, 'miniapp_module_type' => 1])->order('id desc')->find();
        if ($miniappOrder) {
            //查询购买的应用模块id
            $miniappOrder['module'] = MiniappModule::where('id', $miniappOrder['miniapp_module_id'])->find();
            //得到剩余天数
            $miniappOrder['ex_days'] = MiniappTerm::getDaysRemaining($this->uid, null, $miniappOrder['expire_time']);
        }


        $hasBuy = $miniappOrder ? 1 : 0;
        $miniappModules = MiniappModule::where('miniapp_id', $id)->select()->toArray();
        $baseModules = $addModules = [];
        //应用插件
        $plugins = Plugin::where('type', 'like', "%{$detail['dir']}%")->column('*', 'title');
        //插件订单
        $plugin_ids = MemberPluginOrder::where('member_id', $this->user->top_id)->column('plugin_id', 'plugin_id');
        foreach ($plugins as &$value) {
            $value['has_buy'] = 0;
            if (isset($plugin_ids[$value['id']])) $value['has_buy'] = 1;
        }
        $price = [];
        foreach ($miniappModules as &$miniappModule) {
            $price = array_merge($price, array_column($miniappModule['price_list'], 'price'));
            $miniappModule['has_buy'] = 0;
            if ($hasBuy && $miniappModule['id'] == $miniappOrder['miniapp_module_id']) $miniappModule['has_buy'] = 1;
            //1,2全部都是基础功能
            if ($miniappModule['type'] == 1 || $miniappModule['type'] == 2) $baseModules[] = $miniappModule;
        }
        //获取功能套餐组的套餐价格
        $detail['min_price'] = sprintf('%.2f', min($price));
        $detail['max_price'] = sprintf('%.2f', max($price));
        //当前应用版本信息
        $version_info = MiniappService::getVersion($detail['dir']);//应用本地版本
        $price = \app\common\model\member\Wallet::getMoney($this->uid);//当前余额
        //返回路径
        $url_info = [
            'base' => '/manage/member/miniapp/index',
            'base_name' => '应用中心',
        ];
        if ($this->request->isPost()) {
            return $this->success('查询成功', compact('price', 'detail', 'baseModule', 'hasBuy', 'version_info', 'plugins', 'baseModules', 'addModules', 'url_info', 'miniappOrder'));
        }
        View::assign(compact('price', 'detail', 'baseModule', 'hasBuy', 'version_info', 'plugins', 'baseModules', 'addModules', 'url_info', 'miniappOrder'));
        return view();
    }

    /**
     * 应用详情页[前后端分离接口API]
     * @param int $id
     * @return \think\Response|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detailNew($id = 0)
    {
        $detail = $this->model->where(['id' => $id, 'status' => 1])->find();
        if (!$detail) return $this->error('应用不存在');
        //富文本转义
        $detail['content'] = urldecode(urldecode(html_entity_decode($detail['content'])));
        //应用基础功能
        $baseModule = MiniappModule::where(['miniapp_id' => $id, 'type' => 1])->find();
        if (!$baseModule) return $this->error('应用有误,无基础功能');
        if (!$baseModule['price_list']) return $this->error('该应用功能不完整,请联系客服在总后台设置购买套餐');
        //TODO：查询最近购买的基础套餐
        $miniappOrder = MemberMiniappOrder::where(['member_id' => $this->uid, 'miniapp_id' => $id, 'miniapp_module_type' => 1])->order('id desc')->find();
        if ($miniappOrder) {
            //查询购买的应用模块id
            $miniappOrder['module'] = MiniappModule::where('id', $miniappOrder['miniapp_module_id'])->find();
            //得到剩余天数
            $miniappOrder['ex_days'] = MiniappTerm::getDaysRemaining($this->uid, null, $miniappOrder['expire_time']);

            //设置规格名称
            $miniappOrder['price_name']='';
            //查询购买的应用模块id
            $miniappOrder['module'] = MiniappModule::where('id', $miniappOrder['miniapp_module_id'])->find();
            if ($miniappOrder['module'] && isset($miniappOrder['module']['price_list'])) {
                $price_list_new = array_column($miniappOrder['module']['price_list'],null,'uuid');
                if(isset($price_list_new[$miniappOrder['price_uuid']])){
                    $miniappOrder['price_name']=$price_list_new[$miniappOrder['price_uuid']]['title'];
                }
            }
        }


        $hasBuy = $miniappOrder ? 1 : 0;
        $miniappModules = MiniappModule::where('miniapp_id', $id)->select()->toArray();
        $baseModules = $addModules = [];
        //应用插件
        $plugins = Plugin::where('type', 'like', "%{$detail['dir']}%")->column('*', 'title');
        //插件订单
        $plugin_ids = MemberPluginOrder::where('member_id', $this->user->top_id)->column('plugin_id', 'plugin_id');
        foreach ($plugins as &$value) {
            $value['has_buy'] = 0;
            if (isset($plugin_ids[$value['id']])) $value['has_buy'] = 1;
        }
        $price = [];
        foreach ($miniappModules as &$miniappModule) {
            $price = array_merge($price, array_column($miniappModule['price_list'], 'price'));
            $miniappModule['has_buy'] = 0;
            if ($hasBuy && $miniappModule['id'] == $miniappOrder['miniapp_module_id']) $miniappModule['has_buy'] = 1;
            //1,2全部都是基础功能
            if ($miniappModule['type'] == 1 || $miniappModule['type'] == 2) $baseModules[] = $miniappModule;
        }
        //获取功能套餐组的套餐价格
        $detail['min_price'] = sprintf('%.2f', min($price));
        $detail['max_price'] = sprintf('%.2f', max($price));
        //当前应用版本信息
        $version_info = MiniappService::getVersion($detail['dir']);//应用本地版本
        $price = \app\common\model\member\Wallet::getMoney($this->uid);//当前余额
        //返回路径
        $url_info = [
            'base' => '/manage/member/miniapp/index',
            'base_name' => '应用中心',
        ];
        if ($this->request->isPost()) {
            return $this->success('查询成功', compact('price', 'detail', 'baseModule', 'hasBuy', 'version_info', 'plugins', 'baseModules', 'addModules', 'url_info', 'miniappOrder'));
        }
        View::assign(compact('price', 'detail', 'baseModule', 'hasBuy', 'version_info', 'plugins', 'baseModules', 'addModules', 'url_info', 'miniappOrder'));
        return view();
    }

    /**
     * 租户购买应用
     * @param string $id 应用功能id
     * @return \think\Response
     */
    public function buy($id = '')
    {
        if (request()->isPost()) {
            $id = $id ?: request()->post("id/d"); //套餐id
            $price_id = request()->post("price_id/s"); //价格规格id
            $name = request()->post("name/s");//自定义应用名
            $paypwd = request()->post("paypwd/s");//支付密码
            //顶级租户才可以购买
            if ($this->user['parent_id'] != 0) return $this->error('无购买权限');
            //NOTE 验证支付密码
            if (!Member::checkPassword($paypwd, $this->user['safe_password'])) return $this->error('支付密码错误');
            $this->model->startTrans();
            try {
                //判断是购买还是续费，如果是续费调用续费方法
                if (MiniappModule::haveBuy($this->uid, $id)) {
                    //购买
                    $msg = "购买成功";
                    $price_info = [
                        'miniapp_module_id' => $id,
                        'price_id' => $price_id,
                    ];
                    MiniappService::buy($this->uid, $price_info, $name);
                } else {
                    //续费
                    $msg = "续费成功";
                    (new MiniappModule)->renew($id, $price_id, $paypwd, $this->uid);

                }
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error("失败：" . $e->getMessage());
            }
            return $this->success($msg);
        }
    }

    /**
     * 调用微信开放平台设置小程序的业务域名
     * @param string $action get/set 获取/设置小程序服务器域名
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setDomain(string $action = 'set')
    {
        self::isMemberAppAuth();
        if ($this->request->isAjax()) {
            if (!in_array($action, ['add', 'get', 'set', 'delete'])) return $this->error('参数不合法', [], 400019);
            $rel = MemberMiniappAudit::where(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id])->find();
            if (!empty($rel) && $rel->is_commit == 3 && $rel->state == 1) {
                return $this->error('审核中小程序禁止设置业务域名', [], 400020);
            }

            $setParam['action'] = $action;
            //授权给第三方的小程序，其服务器域名只可以为在第三方平台账号中配置的小程序服务器域名
            //设定定位用到的腾讯地图域名
            $setParam['requestdomain'] = ['https://' . $this->request->host(), 'https://apis.map.qq.com'];
            $setParam['wsrequestdomain'] = ['wss://' . $this->request->host()];
            $setParam['uploaddomain'] = ['https://' . $this->request->host()];
            $setParam['downloaddomain'] = ['https://' . $this->request->host()];
            $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
            if (!$mini_program) {
                return $this->error('小程序还未授权,禁止操作', [], 400021);
            }
            $rel = $mini_program->domain->modify($setParam);
            if ($rel['errcode'] > 0) {
                $rel['errcode'] == 85015 && $rel['errmsg'] = "该账号不是小程序账号";
                $rel['errcode'] == 85017 && $rel['errmsg'] = "没有新增域名，请确认小程序已经添加了域名或该域名是否没有在第三方平台添加";
                $rel['errcode'] == 85018 && $rel['errmsg'] = "域名没有在第三方平台设置";
                return $this->error('报错信息:' . $rel['errmsg'], [], 400022);
            }
            $mini_program->domain->setWebviewDomain(['https://' . $this->request->rootDomain()]);  //设置业务域名
            $data['is_commit'] = 2;
            $data['member_miniapp_id'] = $this->member_miniapp_id;
            $data['member_id'] = $this->user['id'];
            MemberMiniappAudit::edit(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id], $data);
            return $this->success('设置域名成功');
        }
    }

    /**
     * 上传代码
     */
    public function upCode()
    {
        self::isMemberAppAuth();
        if ($this->request->isAjax()) {
            $rel = MemberMiniappAudit::where(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id])->find();
            if (!empty($rel) && $rel->is_commit == 3 && $rel->state == 1) {
                return $this->error('审核中小程序禁止设置业务域名', [], 400020);
            }
            //读取小程序信息
            $app = $this->model->where(['id' => $this->member_miniapp->miniapp_id, 'status' => 1])->find();
            if (empty($app)) {
                return $this->error('小程序不存在或暂停服务', [], 400023);
            }
            //上传参数
            $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
            if (!$mini_program) {
                return $this->error('小程序还未授权,禁止操作', [], 400021);
            }
            $extJson = [
                'extAppid' => $this->member_miniapp->miniapp_appid,
                'ext' => [
                    "name" => $this->member_miniapp->appname,
                    "attr" => [
                        'host' => 'https://' . $this->request->host(),
                        'app_name' => $this->miniapp->dir,
                        'service_id' => $this->member_miniapp->service_id,
                    ],
                ],
                "window" => ['navigationBarTitleText' => $this->member_miniapp->appname]
            ];
            //获取可升级的版本
            $update = MemberMiniappTemplate::where(['member_miniapp_id' => $this->member_miniapp->id])->field('template_id,version')->order('template_id desc')->find();
            if (!$update) return $this->error("未找到可上架的小程序代码模板！");
            //上传小程序代码
            $upRel = $mini_program->code->commit($update['template_id'], json_encode($extJson), $update['version'], $this->miniapp->describe);
            if ($upRel['errcode'] != 0) return $this->error('小程序代码提交上传失败：' . $upRel['errmsg'], [], 400024);
            //更新信息
            $data['is_commit'] = 3;
            $data['member_miniapp_id'] = $this->member_miniapp_id;
            $data['member_id'] = $this->user->id;
            $data['template_id'] = $update['template_id'];
            $data['version'] = $update['version'];
            MemberMiniappAudit::edit(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id], $data);
            return $this->success('代码上传成功，请进行下一步！');
        }
    }

    /**
     * 提交审核
     * @access public
     */
    public function submitAudit()
    {
        self::isMemberAppAuth();
        if ($this->request->isGet()) {
            $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
            if (!$mini_program) {
                return $this->error_jump('小程序还未授权,禁止操作');
            }
            $cateRes = $mini_program->code->getCategory();  //获取审核时可填写的类目信息,本接口接口可获取已设置的二级类目及用于代码审核的可选三级类目
            if ($cateRes['errcode'] == -1) {
                return $this->error_jump($cateRes['errcode'] . ':' . $cateRes['errmsg']);
            }
            $page = $mini_program->code->getPage();  //获取已上传的代码的页面列表,通过本接口可以获取由第三方平台上传小程序代码的页面列表；用于提交审核的审核项 的 address 参数
            if ($page['errcode'] != 0) {
                return $this->error_jump($page['errcode'] . ':' . $page['errmsg']);
            }
            $cate = [];
            foreach ($cateRes['category_list'] as $key => $value) {
                $cate[$key]['name'] = empty($value['third_class']) ? $value['first_class'] . '-' . $value['second_class'] : $value['first_class'] . '-' . $value['second_class'] . '-' . $value['third_class'];
                $cate[$key]['id'] = empty($value['third_id']) ? $value['first_id'] . '-' . $value['second_id'] : $value['first_id'] . '-' . $value['second_id'] . '-' . $value['third_id'];
            }
            $view['cate'] = $cate;
            $view['page'] = $page['page_list'];
            $view['id'] = $this->member_miniapp_id;
            View::assign($view);
            return view();
        } else {
            if (request()->isAjax()) {
                $data = [
                    'cate' => $this->request->param('cate[0]/a'),
                    'page' => $this->request->param('page[0]/a'),
                    'name' => $this->request->param('name[0]/a'),
                    'tag' => $this->request->param('tag[0]/a'),
                ];
                //TODO 验证参数
                if ($data['cate']['0'] == "" || $data['page'][0] == "") return $this->error('提交的数据不完善');
                $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
                if (!$mini_program) {
                    return $this->error('小程序还未授权,禁止操作', [], 400021);
                }

                //读取分类
                $getcate = $mini_program->code->getCategory();
                if ($getcate['errcode'] == -1) {
                    return $this->error($getcate['errmsg']);
                }

                //页面一
                $page[0] = ["address" => $data['page'][0], "tag" => $data['tag'][0], "title" => $data['name'][0]];
                $item[0] = array_merge($page[0], $getcate['category_list'][$data['cate']['0']]);

                //提交审核单
                $rel = $mini_program->code->submitAudit($item);
                if ($rel['errcode'] != 0) {
                    return $this->error($rel['errmsg']);
                }
                $code_data['is_commit'] = 3;
                $code_data['state'] = 1;
                $code_data['member_miniapp_id'] = $this->member_miniapp_id;
                $code_data['member_id'] = $this->user->id;
                $code_data['auditid'] = $rel['auditid'];
                MemberMiniappAudit::edit(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id], $code_data);
                return $this->success('提交审核成功', ['url' => url('/manage/member.setting/' . $this->member_miniapp_id)]);
            } else {
                return $this->error('请求方法不对');
            }
        }

    }

    /**
     * 拉取小程序体验二维码
     */
    public function getQrCode()
    {
        if (request()->isAjax()) {
            $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
            if (!$mini_program) {
                return $this->error('小程序还未授权,禁止操作', [], 400021);
            }
            try {
                $qrcode = $mini_program->code->getQrCode();
            } catch (\Exception $e) {
                return $this->error('小程序还未授权,禁止操作', [], 400021);
            }
            $data['trial_qrcode'] = $this->saveQrCode($qrcode, 'miniapp_' . $this->member_miniapp_id);
            $data['member_miniapp_id'] = $this->member_miniapp_id;
            $data['member_id'] = $this->user->id;
            MemberMiniappAudit::edit(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id], $data);
            return $this->success('读取体验二维码成功', ['qr_url' => $data['trial_qrcode']]);
        } else {
            return $this->error('读取体验二维码失败');
        }
    }

    /**
     * 查询指定auditid的小程序审核状态
     */
    public function getAuditStatus()
    {
        if (request()->isAjax()) {
            $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
            if (!$mini_program) {
                return $this->error('小程序还未授权,禁止操作', [], 400021);
            }
            $rel = MemberMiniappAudit::where(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id])->find();
            if (!empty($rel) && $rel->is_commit == 3 && $rel->state == 1) {
                $auditId = $rel['auditid'];
            }
            if (!isset($auditId)) return $this->error('小程序尚未提交审核！');
            try {
                $status = $mini_program->code->getAuditStatus($auditId);
            } catch (\Exception $e) {
                return $this->error($e->getMessage());
            }
            if ($status['errcode'] != 0) {
                return $this->error($status['errmsg']);
            }
            $msgArray = ['审核成功', '审核被拒绝', '审核中', '已撤回', '审核延后'];
            $statusMsg = $msgArray[$status['status']];
            return $this->success('查询结果：' . $statusMsg, ['status' => $status['status'], 'msg' => $statusMsg]);
        } else {
            return $this->error('获取审核状态失败');
        }
    }

    /**
     * 强制撤销审核
     * @access public
     */
    public function resetAudit()
    {
        if (request()->isAjax()) {
            $mini_program = WechatProgram::getWechatObj($this->member_miniapp_id);
            if (!$mini_program) {
                return $this->error('小程序还未授权,禁止操作', [], 400021);
            }
            $rel = $mini_program->code->withdrawAudit();
            if ($rel['errcode'] == 0) {
                $data['is_commit'] = 2;
                $data['state'] = 0;
                $data['member_miniapp_id'] = $this->member_miniapp_id;
                $data['member_id'] = $this->user->id;
                MemberMiniappAudit::edit(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id], $data);
                return $this->success('撤回成功');
            } else {
                return $this->error('撤回失败' . $rel['errmsg']);
            }
        } else {
            return $this->error('请求方法错误');
        }
    }

    /**
     * 发布小程序代码 需要先审核成功
     */
    public function publishCode()
    {
        if (request()->isAjax()) {
            $rel = WechatProgram::getWechatObj($this->member_miniapp_id)->code->release();
            switch ($rel['errcode']) {
                case 0:
                    //修改发布状态
                    MemberMiniappAudit::edit(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id], ['is_commit' => 4, 'state' => 0, 'member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id]);
                    $rel = MemberMiniappAudit::where(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id])->find();
                    if (empty($rel) || !isset($rel['template_id']) || !isset($rel['version'])) return $this->error('提交的代码版本信息有误');
                    //同步用户已购买应用版本信息
                    MemberMiniapp::where(['id' => $this->member_miniapp_id])->update(['template_id' => $rel['template_id'], 'version' => $rel['version'], 'update_time' => time()]);
                    return $this->success('发布成功');
                    break;
                case 85019:
                    return $this->error('没有审核版本');
                    break;
                case 85020:
                    return $this->error('审核状态未满足发布');
                    break;
                case -1:
                    return $this->error('系统繁忙');
                    break;
                default:
                    return $this->error($rel['errmsg']);
                    break;
            }
        } else {
            return $this->error('请求方法错误');
        }
    }

    /**
     * 直接把内容保存到服务器
     * @return string
     */
    private function saveQrCode($str, $qrname = 'qrcode')
    {
        $dir = public_path('res/qrcode') . Inspect::filter_escape($qrname);
        is_mkdir($dir);
        $qrname = $dir . '.png';
        file_put_contents($qrname, $str);
        return '/' . str_replace('\\', '/', substr($qrname, strlen(public_path())));
    }

    /**
     * 应用登录信息
     */
    public function miniappLogin(Request $request)
    {
        $token = get_token($request);

        $rootPath = app()->getRootPath() . 'buwang' . DS . 'util'. DS. 'js'. DS . 'routerjson.json';
        $content = file_get_contents($rootPath);

        return $this->success('success', ['token' => $token,'content' => json_decode($content)]);
    }
}
